package com.ecp.commons.db;

import java.util.Arrays;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoDB {
	public MongoClient	mongo	= null;
	public DB			db		= null;

	private String		address;
	private String		dbname;
	private int			needAuth;
	private String		username;
	private String		password;

	public void setAddress(String address) {
		this.address = address;
	}

	public void setDbname(String dbname) {
		this.dbname = dbname;
	}

	public void setNeedAuth(int needAuth) {
		this.needAuth = needAuth;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public synchronized DB getMongoDB() {
		if (mongo == null || db == null) {
			try {
				MongoClientOptions.Builder options = new MongoClientOptions.Builder();
				options.socketKeepAlive(true);
				//options.connectTimeout(60000);
				options.connectionsPerHost(50);// default: 10
				options.threadsAllowedToBlockForConnectionMultiplier(20); // default: 5
				// 50 * 20 = 1000;
				if (needAuth == 1) {
					MongoCredential cridential = MongoCredential.createMongoCRCredential(username, dbname,
							password.toCharArray());
					mongo = new MongoClient(Arrays.asList(new ServerAddress(address)), Arrays.asList(cridential),
							options.build());
				} else {
					mongo = new MongoClient(address, options.build());
				}
				db = mongo.getDB(dbname);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return db;
	}

	public synchronized void closeDB() {
		db = null;
		if (mongo != null) {
			mongo.close();
		}
	}

	protected synchronized void finalize() {
		System.out.println("MongoDB.finalize");
		db = null;
		if (mongo != null) {
			mongo.close();
		}
	}
}
